import { defineStore } from 'pinia'
import { login, logout, getUserInfo, refreshToken, updatePassword, updateProfile } from '@/api/auth'
import { ElMessage } from 'element-plus'
import router from '@/router'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    refreshToken: localStorage.getItem('refreshToken') || '',
    tokenExpireTime: localStorage.getItem('tokenExpireTime') || 0,
    userInfo: JSON.parse(localStorage.getItem('userInfo')) || null,
    roles: JSON.parse(localStorage.getItem('roles')) || [],
    permissions: JSON.parse(localStorage.getItem('permissions')) || []
  }),
  getters: {
    isLoggedIn: (state) => !!state.token,
    isAdmin: (state) => state.roles.includes('admin'),
    userAvatar: (state) => state.userInfo?.avatar,
    userName: (state) => state.userInfo?.nickname || state.userInfo?.username
  },
  actions: {
    // 用户登录
    async userLogin(loginForm) {
      try {
        const res = await login(loginForm)
        this.token = res.data.token
        this.refreshToken = res.data.refreshToken
        this.tokenExpireTime = res.data.tokenExpireTime
        localStorage.setItem('token', res.data.token)
        localStorage.setItem('refreshToken', res.data.refreshToken)
        localStorage.setItem('tokenExpireTime', res.data.tokenExpireTime)
        ElMessage.success('登录成功')
        return res
      } catch (error) {
        ElMessage.error(error.msg || '登录失败')
        throw error
      }
    },

    // 用户注销
    async userLogout() {
      try {
        await logout()
        this.clearAuthInfo()
        ElMessage.success('退出成功')
        router.push('/login')
      } catch (error) {
        ElMessage.error(error.msg || '退出失败')
        console.error('退出失败', error)
      }
    },

    // 获取当前用户信息
    async fetchUserInfo() {
      try {
        const res = await getUserInfo()
        this.userInfo = res.data
        this.roles = res.data.roles || []
        this.permissions = res.data.permissions || []
        localStorage.setItem('userInfo', JSON.stringify(res.data))
        localStorage.setItem('roles', JSON.stringify(res.data.roles || []))
        localStorage.setItem('permissions', JSON.stringify(res.data.permissions || []))
        return res
      } catch (error) {
        ElMessage.error(error.msg || '获取用户信息失败')
        console.error('获取用户信息失败', error)
        this.clearAuthInfo() // 获取用户信息失败时清除认证信息
        router.push('/login')
        throw error
      }
    },

    // 刷新令牌
    async userRefreshToken() {
      try {
        const res = await refreshToken({ refreshToken: this.refreshToken })
        this.token = res.data.token
        this.refreshToken = res.data.refreshToken
        this.tokenExpireTime = res.data.tokenExpireTime
        localStorage.setItem('token', res.data.token)
        localStorage.setItem('refreshToken', res.data.refreshToken)
        localStorage.setItem('tokenExpireTime', res.data.tokenExpireTime)
        return res
      } catch (error) {
        ElMessage.error(error.msg || '刷新令牌失败，请重新登录')
        console.error('刷新令牌失败', error)
        this.clearAuthInfo()
        router.push('/login')
        throw error
      }
    },

    // 修改个人密码
    async updatePersonalPassword(data) {
      try {
        await updatePassword(data)
        ElMessage.success('密码修改成功，请重新登录')
        this.clearAuthInfo()
        router.push('/login')
      } catch (error) {
        ElMessage.error(error.msg || '密码修改失败')
        throw error
      }
    },

    // 修改个人资料
    async updatePersonalProfile(data) {
      try {
        await updateProfile(data)
        ElMessage.success('个人资料修改成功')
        await this.fetchUserInfo() // 刷新用户信息
      } catch (error) {
        ElMessage.error(error.msg || '个人资料修改失败')
        throw error
      }
    },

    // 清除认证信息
    clearAuthInfo() {
      this.token = ''
      this.refreshToken = ''
      this.tokenExpireTime = 0
      this.userInfo = null
      this.roles = []
      this.permissions = []
      localStorage.removeItem('token')
      localStorage.removeItem('refreshToken')
      localStorage.removeItem('tokenExpireTime')
      localStorage.removeItem('userInfo')
      localStorage.removeItem('roles')
      localStorage.removeItem('permissions')
    }
  }
}) 